package com.main.zlw.zlwaudiorecorder;

import com.main.zlw.zlwaudiorecorder.slice.MainAbilitySlice;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.window.dialog.ToastDialog;
import ohos.bundle.AbilityInfo;
import ohos.bundle.IBundleManager;

public class MainAbility extends Ability {
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setMainRoute(MainAbilitySlice.class.getName());
        if (verifySelfPermission("ohos.permission.READ_MEDIA") != IBundleManager.PERMISSION_GRANTED
        &&verifySelfPermission("ohos.permission.WRITE_MEDIA") != IBundleManager.PERMISSION_GRANTED
                &&verifySelfPermission("ohos.permission.MICROPHONE") != IBundleManager.PERMISSION_GRANTED
                &&verifySelfPermission("ohos.permission.RECORD_AUDIO") != IBundleManager.PERMISSION_GRANTED
        ) {
            // 应用未被授予权限
            if (canRequestPermission("ohos.permission.WRITE_MEDIA")) {
                // 是否可以申请弹框授权(首次申请或者用户未选择禁止且不再提示)
                requestPermissionsFromUser(
                        new String[] { "ohos.permission.READ_MEDIA", "ohos.permission.WRITE_MEDIA",
                                "ohos.permission.MICROPHONE","ohos.permission.RECORD_AUDIO"} , 1);
            } else {
                // 显示应用需要权限的理由，提示用户进入设置授权
            }
        } else {
            // 权限已被授予
        }
    }

    @Override
    public void onRequestPermissionsFromUserResult (int requestCode, String[] permissions, int[] grantResults){
        switch (requestCode) {
            case 1: {
                // 匹配requestPermissions的requestCode
                if (grantResults.length > 0
                        && grantResults[0] == IBundleManager.PERMISSION_GRANTED) {
                    // 权限被授予
                    // 注意：因时间差导致接口权限检查时有无权限，所以对那些因无权限而抛异常的接口进行异常捕获处理
                } else {
                    // 权限被拒绝
                    new ToastDialog(this).setText("权限被禁止后将无法使用").show();
                    terminateAbility();
                }
                return;
            }
        }
    }
}
